package org.example.secondkill.service.impl;

import org.example.secondkill.domain.Order;
import org.example.secondkill.redis.RedisService;
import org.example.secondkill.redis.SecondKillKey;
import org.example.secondkill.service.IGoodsService;
import org.example.secondkill.service.IKillService;
import org.example.secondkill.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class KillService implements IKillService {
    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedisService redisService;

    /**
     * 减库存-下订单-写入秒杀订单
     */
    @Override
    @Transactional
    public void placeAnOrder(long userId, long goodsId) {
        orderService.createOrder(userId, goodsId);
//        boolean res = goodsService.reduceStock(goods.getId());
//        if (res) {
//            return orderService.createOrder(userId, goods);
//        } else {
//            // 减库存失败 ==> 当前商品已经卖完，设置为不可再秒杀，即修改Redis中的值
//            setTimeOver(goods.getId());
//            return null;
//        }
    }

    /**
     * 获取订单的结果，
     * 成功则返回订单号；
     * 订单不存在且仍可以秒杀，则返回0；
     * 订单不存在且不可再秒杀，则返回-1；
     */
    @Override
    public Order getOrderResult(long userId, long goodsId) {
        Order order = orderService.getOrderByUserIdAndGoodsId(userId, goodsId);
        if (order != null) {
            return order;
        } else {
            if (getTimeOver(goodsId)) {
                // 当前商品已经结束秒杀了
                return null;
            } else {
                return null;
            }
        }
    }

    @Override
    public void deleteAllOrders() {
        orderService.deleteAllOrders();
    }

    private void setTimeOver(long goodsId) {
        redisService.set(
                SecondKillKey.isGoodsOver,
                "" + goodsId,
                true
        );
    }

    private boolean getTimeOver(long goodsId) {
        return redisService.exists(
                SecondKillKey.isGoodsOver,
                "" + goodsId
        );
    }
}
